package net.wicp.tams.component.components;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.json.JSONArray;

import net.wicp.tams.commons.apiext.JSONUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.commons.callback.IConvertValue;
import net.wicp.tams.commons.callback.impl.convertvalue.ConvertValueEnum;
import net.wicp.tams.component.components.ComboBox;
import net.wicp.tams.component.services.ISupportedLocales;

/****
 * 枚举类型的下拉组件
 * 
 * @author andy.zhou
 *
 */
public class ComboBoxEnum extends ComboBox {
	/***
	 * 要组装的枚举
	 */
	@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
	private String enumClass;
	/***
	 * 包含的项
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String include;
	/***
	 * 排除的项，优先级大于包含的项
	 */
	@Parameter(required = false, defaultPrefix = BindingConstants.LITERAL)
	private String remove;

	@Inject
	private ISupportedLocales locale;

	@SetupRender
	private void init() throws ClassNotFoundException {
		resources.storeRenderVariable(valueFieldVarName, "name");
		resources.storeRenderVariable(textFieldVarName, "text");
		Class cls = (Class<Enum>) Class.forName(enumClass);
		Object[] objs = cls.getEnumConstants();
		if (ArrayUtils.isEmpty(objs)) {
			super.setData(new JSONArray("[]"));
		} else {
			List<Object> list = Arrays.asList(objs);

			// 包括项
			if (resources.isBound("include") && StringUtil.isNotNull(include)) {
				final String[] ins = include.split(",");
				list = (List<Object>) CollectionUtils.select(list, new Predicate() {
					@Override
					public boolean evaluate(Object object) {
						Enum temobj = (Enum) object;
						return ArrayUtils.contains(ins, temobj.name());
					}
				});
			}
			// 排除项
			if (resources.isBound("remove") && StringUtil.isNotNull(remove)) {
				final String[] outs = remove.split(",");
				CollectionUtils.filter(list, new Predicate() {
					@Override
					public boolean evaluate(Object object) {
						Enum temobj = (Enum) object;
						return !ArrayUtils.contains(outs, temobj.name());
					}
				});
			}

			String lan = locale.getCurLocale().getLanguage();
			String filedName = StringUtil.isNull(lan) ? "desc" : String.format("desc_%s", lan);
			IConvertValue<String> cv = new ConvertValueEnum(list.toArray(), lan);
			String curData = JSONUtil.getJsonForList(list, new IConvertValue[] { null, cv }, "name,",
					filedName + ",text");
			super.setData(new JSONArray(curData));
		}

	}
}
